package com.hmy.finance.job.receipt;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmy.ccp.common.dto.ContextUserInfo;
import com.hmy.ccp.error.exception.HMYRuntimeException;
import com.hmy.ccp.starter.web.utils.UserContextUtil;
import com.hmy.finance.api.bo.core.request.enums.ReceiptOffsetBillStatusEnum;
import com.hmy.finance.dal.mapper.receipt.ReceiptOffsetBillMapper;
import com.hmy.finance.dal.po.receipt.ReceiptOffsetBillPo;
import com.hmy.finance.service.receipt.ReceiptOffsetBillService;
import com.hmy.finance.service.receipt.dto.receiptOffset.ReceiptBillOffsetHandlerDto;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class ManualOffsetBillJobHandler extends IJobHandler {

    @Resource
    private ReceiptOffsetBillService receiptOffsetBillService;

    @Resource
    private ReceiptOffsetBillMapper receiptOffsetBillMapper;

    @Override
    @XxlJob("ManualOffsetBillJobHandler")
    public void execute() {
        String param = XxlJobHelper.getJobParam();
        ReceiptBillOffsetHandlerDto receiptBillOffsetHandlerDto = JSON.parseObject(param, ReceiptBillOffsetHandlerDto.class);
        Boolean result = receiptOffsetBillService.doReceiptBillOffsetHandler(receiptBillOffsetHandlerDto);
        log.info("ManualOffsetBillJobHandler:result {}", result);
        if (result) {
            ReceiptOffsetBillPo updatePo = new ReceiptOffsetBillPo();
            updatePo.setBillStatus(ReceiptOffsetBillStatusEnum.OFFSET_SUCCESS.getStatusCode());
            updatePo.setUpdaterName("system");
            updatePo.setUpdaterId(9999L);

            LambdaQueryWrapper<ReceiptOffsetBillPo> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(ReceiptOffsetBillPo::getIsDeleted, 0);
            updateWrapper.eq(ReceiptOffsetBillPo::getReceiptOffsetBillId, receiptBillOffsetHandlerDto.getReceiptOffsetBillId());
            int update = receiptOffsetBillMapper.update(updatePo, updateWrapper);
            if (update <= 0) {
                throw new HMYRuntimeException(506800025);
            }
            log.info("ManualOffsetBillJobHandler:Response {}", update);
        }
    }

}
